package com.fq.rpc;

import com.fq.rpc.task.ConsumerIInvokeTask;
import com.fq.rpc.util.ConfigMap;
import org.I0Itec.zkclient.ZkClient;

import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Random;

/**
 * @author jifang
 * @since 16/8/14 上午11:46.
 */
public class ConsumerClient {

    private static ConsumerClient instance = new ConsumerClient();

    public static ConsumerClient getInstance() {
        return instance;
    }

    private static final String PATH = "/mi.rpc/%s/";

    private static ZkClient zk;

    static {
        zk = new ZkClient(ConfigMap.getClient("zk.servers"));
    }

    private String getAddress(String name) {
        List<String> children = zk.getChildren(String.format(PATH, name));
        int index = new Random().nextInt(children.size());
        return children.get(index);
    }

    @SuppressWarnings("all")
    public <T> T subscribe(Class<T> inter) {
        checkInterface(inter);
        String[] address = getAddress(inter.getName()).split(":");
        String ip = address[0];
        int port = Integer.valueOf(address[1]);

        return (T) Proxy.newProxyInstance(inter.getClassLoader(), new Class[]{inter}, new ConsumerIInvokeTask(inter, ip, port));
    }

    private void checkInterface(Class<?> inter) {
        if (inter == null || !inter.isInterface()) {
            throw new IllegalArgumentException("inter Mast a interface class");
        }
    }
}
